package com.atguigu.gulimall.member.interceptor;

import com.atguigu.common.constant.AuthServiceConstant;
import com.atguigu.common.vo.MemberRespVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 拦截器
 *  登录拦截
 */
@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberRespVo> threadLocal = new ThreadLocal<>();

    /**
     * 登录拦截，登录后才能访问该服务
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1、额外放行一些请求
        String uri = request.getRequestURI();
        //放行URI格式是这样的请求：/member/**
        boolean match = new AntPathMatcher().match("/member/**", uri);//判断uri是否符合相应格式
        if (match){
            return true;
        }

        //2、只放行登录后的请求
        HttpSession session = request.getSession();
        MemberRespVo loginUser = (MemberRespVo) session.getAttribute(AuthServiceConstant.LOGINUSER);
        if (loginUser!=null){
            //已登录
            threadLocal.set(loginUser);
            return true;
        }else {
            //未登录就去登录
            session.setAttribute("msg","请登录");
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
}
